/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.dy.yunying.biz.controller.hongbao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.constant.Constant;
import com.dy.yunying.api.entity.hongbao.HbActivity;
import com.dy.yunying.api.entity.hongbao.HbActivityDynamicType;
import com.dy.yunying.api.entity.hongbao.HbCashLimit;
import com.dy.yunying.api.enums.ActivityStatusEnum;
import com.dy.yunying.api.req.hongbao.*;
import com.dy.yunying.api.resp.hongbao.NodeData;
import com.dy.yunying.api.vo.hongbao.ActivityVo;
import com.dy.yunying.biz.config.CheckRepeatSubmit;
import com.dy.yunying.biz.service.hongbao.ActivityService;
import com.dy.yunying.biz.service.hongbao.HbActivityDynamicTypeService;
import com.dy.yunying.biz.utils.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 活动表
 *
 * @author yuwenfeng
 * @date 2021-10-23 10:31:18
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/activity")
@Api(value = "activity", tags = "活动管理")
@Slf4j
public class ActivityController {

	private final ActivityService activityService;

	private final HbActivityDynamicTypeService hbActivityDynamicTypeService;

	@ApiOperation(value = "活动分页查询", notes = "活动分页查询")
	@GetMapping("/selectActivityPage")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_get')")
	public R<Page<ActivityVo>> selectActivityPage(Page<HbActivity> page, @Valid SelectActivityPageReq activityPageReq) {
		try {
			QueryWrapper<SelectActivityPageReq> query = new QueryWrapper<SelectActivityPageReq>();
			if (StringUtils.isNotBlank(activityPageReq.getActivityName())) {
				query.and(wrapper -> wrapper.like("ha.id", activityPageReq.getActivityName()).or().like("ha.activity_name", activityPageReq.getActivityName()));
			}
			if (StringUtils.isNotBlank(activityPageReq.getStartTime())) {
				query.ge("DATE_FORMAT(ha.start_time,'%Y-%m-%d')", activityPageReq.getStartTime());
			}
			if (StringUtils.isNotBlank(activityPageReq.getFinishTime())) {
				query.le("DATE_FORMAT(ha.start_time,'%Y-%m-%d')", activityPageReq.getFinishTime());
			}
			if (StringUtils.isNotBlank(activityPageReq.getGameName())) {
				List<Long> ids = activityService.selectActivityByGame(activityPageReq.getGameName());
				if (CollectionUtils.isNotEmpty(ids)) {
					query.in("ha.id", ids);
				} else {
					ids = new ArrayList<Long>();
					ids.add(0L);
					query.in("ha.id", ids);
				}
			}
			if (null != activityPageReq.getActivityStatus()) {
				query.eq("ha.activity_status", activityPageReq.getActivityStatus());
				if (ActivityStatusEnum.ACTIVITING.getStatus().equals(activityPageReq.getActivityStatus())) {
					query.ge("DATE_FORMAT(DATE_ADD(ha.finish_time,INTERVAL ha.valid_days DAY),'%Y-%m-%d %H:%i:%S')", DateUtils.getcurrentTime());
				}
			}
			//活动动态类型Id
			if (null != activityPageReq.getDynamicTypeId()) {
				query.eq("ha.dynamic_type_id", activityPageReq.getDynamicTypeId());
			}
			//起始条件查询: 0活跃角色 1创建角色
			if(null != activityPageReq.getRoleType()){
				query.eq("ha.role_type", activityPageReq.getRoleType());
			}


			query.eq("ha.activity_type", activityPageReq.getActivityType());
			query.eq("ha.deleted", Constant.DEL_NO);
			if (StringUtils.isNotBlank(activityPageReq.getOrderFile()) && StringUtils.isNotBlank(activityPageReq.getOrderType())) {
				if (Constant.ORDER_ASC.equalsIgnoreCase(activityPageReq.getOrderType())) {
					query.orderByAsc(activityPageReq.getOrderFile());
				} else {
					query.orderByDesc(activityPageReq.getOrderFile());
				}
			} else {
				query.orderByDesc("id");
			}
			return R.ok(activityService.selectActivityPage(page, query));
		} catch (Exception e) {
			log.error("活动管理-分页查询-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@CheckRepeatSubmit
	@ApiOperation(value = "新增活动", notes = "新增活动")
	@SysLog("新增活动")
	@PostMapping("/addActivity")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_add')")
	public R addActivity(@Valid @RequestBody ActivityReq activityReq) {
		try {
			return activityService.addActivity(activityReq);
		} catch (Exception e) {
			log.error("活动管理-新增活动-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@CheckRepeatSubmit
	@ApiOperation(value = "编辑活动", notes = "编辑活动")
	@SysLog("编辑活动")
	@PostMapping("/editActivity")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_edit') or @pms.hasPermission('hongbao_hbactivity_onlineedit')")
	public R editActivity(@Valid @RequestBody ActivityReq activityReq) {
		try {
			return activityService.editActivity(activityReq);
		} catch (Exception e) {
			log.error("活动管理-编辑活动-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@CheckRepeatSubmit
	@ApiOperation(value = "复制活动", notes = "复制活动")
	@SysLog("复制活动")
	@PostMapping("/copyActivity")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_copy')")
	public R copyActivity(@Valid @RequestBody CopyActivityReq activityReq) {
		try {
			return activityService.copyActivity(activityReq);
		} catch (Exception e) {
			log.error("活动管理-复制活动-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@ApiOperation(value = "活动上下线", notes = "活动上线")
	@SysLog("活动上线")
	@PostMapping("/onlineActivity")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_online')")
	public R onlineActivity(@Valid @RequestBody OnlineActivityReq activityReq) {
		try {
			return activityService.onlineActivity(activityReq);
		} catch (Exception e) {
			log.error("活动管理-活动上线-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@ApiOperation(value = "活动批量修改kv图", notes = "活动批量修改kv图")
	@SysLog("活动批量修改kv图")
	@PostMapping("/editKvpicActivity")
	public R editKvpicActivity(@Valid @RequestBody KvpicActivityReq kvpicActivityReq) {
		try {
			return activityService.editKvpicActivity(kvpicActivityReq);
		} catch (Exception e) {
			log.error("活动管理-活动上线-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}


	@CheckRepeatSubmit
	@ApiOperation(value = "设置提现限制", notes = "设置提现限制")
	@SysLog("设置提现限制")
	@PostMapping("/editCashLimit")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_limit')")
	public R editCashLimit(@Valid @RequestBody SetCashLimitReq activityReq) {
		try {
			return activityService.editCashLimit(activityReq);
		} catch (Exception e) {
			log.error("活动管理-活动上线-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@ApiOperation(value = "游戏树形列表", notes = "游戏树形列表")
	@GetMapping("/selectGameTree")
	//@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_game')")
	public R<List<NodeData>> selectGameTree() {
			try {
			return R.ok(activityService.selectGameTree());
		} catch (Exception e) {
			log.error("活动管理-游戏树形列表-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@ApiOperation(value = "区服树形列表", notes = "区服树形列表")
	@GetMapping("/selectAreaTree")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_area')")
	public R<List<NodeData>> selectAreaTree() {
		try {
			return R.ok(activityService.selectAreaTree());
		} catch (Exception e) {
			log.error("活动管理-区服树形列表-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@ApiOperation(value = "渠道树形列表", notes = "渠道树形列表")
	@GetMapping("/selectChannelTree")
	//@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_channel')")
	public R<List<NodeData>> selectChannelTree() {
		try {
			return R.ok(activityService.selectChannelTree());
		} catch (Exception e) {
			log.error("活动管理-渠道树形列表-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@ApiOperation(value = "根据父游戏ID获取区服树形列表", notes = "根据父游戏ID获取区服树形列表")
	@GetMapping("/selectAreaTreeByPgameIds")
//	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_area')")
	public R<List<NodeData>> selectAreaTreeByPgameIds(@Valid String pGgmeIds) {
		try {
			return activityService.selectAreaTreeByPgameIds(pGgmeIds);
		} catch (Exception e) {
			log.error("活动管理-根据父游戏ID获取区服树形列表-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@ApiOperation(value = "根据活动ID和提现类型获取提现规则", notes = "根据活动ID和提现类型获取提现规则")
	@GetMapping("/selectCashLimitByAidAndType")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_limit')")
	public R<HbCashLimit> selectCashLimitByAidAndType(@Valid SelectCashLimitReq req) {
		try {
			return activityService.selectCashLimitByAidAndType(req);
		} catch (Exception e) {
			log.error("活动管理-根据活动ID和提现类型获取提现规则-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	/**
	 * 红包活动下拉列表查询
	 *
	 * @return
	 */
	@PostMapping("/selectActivityList")
	public R<List<HbActivity>> selectActivityList(@RequestBody SelectActivityPageReq activityReq) {
		final List<HbActivity> activityList = activityService.selectActivityList(activityReq);
		return R.ok(activityList);
	}


	@CheckRepeatSubmit
	@ApiOperation(value = "活动动态类型维护", notes = "活动动态类型维护")
	@SysLog("活动动态类型维护")
	@PostMapping("/saveOrUpdateDynamicType")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_dynamic_type')")
	public R saveOrUpdateDynamicType(@Valid @RequestBody DynamicTypeReq dynamicTypeReq) {
		try {
			return activityService.saveOrUpdateDynamicType(dynamicTypeReq);
		} catch (Exception e) {
			log.error("活动管理-活动动态类型维护-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}


	@CheckRepeatSubmit
	@ApiOperation(value = "活动动态类型删除", notes = "活动动态类型删除")
	@SysLog("活动动态类型删除")
	@PostMapping("/deleteDynamicType")
	@PreAuthorize("@pms.hasPermission('hongbao_hbactivity_dynamic_type')")
	public R deleteDynamicType(@RequestBody DynamicTypeReq req) {
		try {
			if(req.getId() == null || req.getActivityType() == null){
				return R.failed("参数丢失");
			}
			return activityService.deleteDynamicType(req);
		} catch (Exception e) {
			log.error("活动管理-活动动态类型维护-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}


	/**
	 * 红包活动动态类型列表查询
	 *
	 * @return
	 */
	@PostMapping("/selectDynamicTypeList")
	public R<List<HbActivityDynamicType>> selectDynamicTypeList(@RequestBody DynamicTypeReq req) {

		QueryWrapper<HbActivityDynamicType> query = new QueryWrapper<>();

		query.lambda().eq(req.getActivityType() != null, HbActivityDynamicType::getActivityType, req.getActivityType())
				.eq(HbActivityDynamicType :: getDeleted, 0)
				.orderByAsc(HbActivityDynamicType::getSort,HbActivityDynamicType::getId);

		List<HbActivityDynamicType> dynamicTypeList = hbActivityDynamicTypeService.list(query);
		return R.ok(dynamicTypeList);
	}


}
